﻿using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.Bill.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;

namespace DzInfo.FormPlugIn.ND
{
    [Description("ND:组装拆卸单成本比例"), HotUpdate]
    public class ZZCXCBBL : AbstractBillPlugIn
    {
        public override void BeforeSave(BeforeSaveEventArgs e)
        {
            base.BeforeSave(e);
            var obj = this.Model.DataObject;
            DynamicObject billnoType = obj["FBillTypeID"] as DynamicObject;
            string typeNumber = billnoType?["number"]?.ToString() ?? "";
            if (typeNumber != "KLXXD") return;

            DynamicObjectCollection cpRows = obj["ProductEntity"] as DynamicObjectCollection;
            foreach (var cpRow in cpRows)
            {
                DynamicObject cpMat = cpRow["MaterialID"] as DynamicObject;
                var cpfz = cpMat?["MaterialGroup"] as DynamicObject;
                string fzNumber = cpfz?["number"]?.ToString() ?? "";
                DynamicObjectCollection MaterialBase = cpMat?["MaterialBase"] as DynamicObjectCollection;
                var jbdw = MaterialBase?[0]?["BaseUnitId"] as DynamicObject;
                string dwNumber = jbdw?["number"]?.ToString() ?? "";

                if (fzNumber != "M37SRM" || dwNumber != "kg") continue;

                DynamicObjectCollection mxRows = cpRow["STK_ASSEMBLYSUBITEM"] as DynamicObjectCollection;
                if (mxRows == null || mxRows.Count == 0) continue;

                // 收集所有KCZT01_SYS状态的行数据（索引和值）
                var validRows = new List<(int Index, decimal Value)>();
                for (int i = 0; i < mxRows.Count; i++)
                {
                    var mxRow = mxRows[i];
                    var kczt = mxRow["FStockStatusIDSETY"] as DynamicObject;
                    string ztNumber = kczt?["number"]?.ToString() ?? "";
                    if (ztNumber != "KCZT01_SYS") continue;

                    if (!decimal.TryParse(mxRow["F_NDD_Decimal"]?.ToString(), out decimal f_ndd))
                        continue;

                    validRows.Add((i, f_ndd));
                }

                // 计算有效行的总值
                decimal zjzz = validRows.Sum(r => r.Value);
                if (zjzz == 0) continue;

                // 计算比例并处理小数位尾差
                decimal totalPercent = 0;
                decimal accumulated = 0;
                for (int j = 0; j < validRows.Count; j++)
                {
                    var (index, value) = validRows[j];
                    decimal rawPercent = value / zjzz * 100;

                    // 保留两位小数（四舍五入）
                    decimal roundedPercent = Math.Round(rawPercent, 2);

                    // 最后一行特殊处理：用100减去前面的总和
                    if (j == validRows.Count - 1)
                    {
                        // 计算尾差补偿值（确保总和100）
                        decimal adjustedPercent = 100 - accumulated;
                        // 处理可能的负值（理论上不应出现）
                        adjustedPercent = Math.Max(adjustedPercent, 0);
                        this.Model.SetValue("FCostProportion", Math.Round(adjustedPercent, 2), index);
                    }
                    else
                    {
                        this.Model.SetValue("FCostProportion", roundedPercent, index);
                        accumulated += roundedPercent;
                    }
                }
            }
        }
    }
}